<template>
  <div class="weather-monitor-container">
    <!-- 搜索区域 -->
    <el-card class="search-card">
      <div class="search-bar">
        <label class="search-module-label">气象监测点管理</label>
        <el-form :model="queryParams" :inline="true" class="search-form">
          <el-form-item label="事件名称">
            <el-select
              v-model="queryParams.eventName"
              placeholder="请选择事件名称"
              style="width: 180px"
            >
              <el-option
                label="2024年12月11日汤营超桥"
                value="20241211tycq"
              ></el-option>
              <el-option
                label="2024年12月15日河道治理"
                value="20241215hdzl"
              ></el-option>
              <el-option
                label="2024年12月20日环境监测"
                value="20241220hjjc"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="监测点名称">
            <el-input
              v-model="queryParams.pointName"
              placeholder="请输入监测点名称"
              style="width: 180px"
              clearable
            />
          </el-form-item>
          <el-form-item label="温度范围">
            <el-input-number
              v-model="queryParams.minTemp"
              :min="0"
              :max="100"
              placeholder="最低"
              style="width: 80px; margin-right: 10px"
            />
            <span style="margin-right: 10px">-</span>
            <el-input-number
              v-model="queryParams.maxTemp"
              :min="0"
              :max="100"
              placeholder="最高"
              style="width: 80px"
            />
          </el-form-item>
          <el-form-item>
            <el-button
              type="primary"
              icon="el-icon-search"
              @click="handleSearch"
              >查询</el-button
            >
            <el-button
              icon="el-icon-refresh-right"
              @click="handleReset"
              style="margin-left: 8px"
              >重置</el-button
            >
          </el-form-item>
        </el-form>
      </div>
    </el-card>

    <!-- 操作区域 + 表格 -->
    <el-card class="table-card">
      <div class="operate-bar">
        <el-button type="primary" plain icon="el-icon-plus" @click="handleAdd"
          >新增</el-button
        >
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          @click="handleBatchUpdate"
          :disabled="selectedRows.length !== 1"
          >修改</el-button
        >
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          @click="handleBatchDelete"
          :disabled="selectedRows.length === 0"
          >删除</el-button
        >
      </div>

      <el-table
        :data="tableData"
        border
        stripe
        :height="tableHeight"
        @selection-change="handleSelectionChange"
        :header-cell-style="{ background: '#f5f7fa', fontWeight: 600 }"
        style="width: 100%"
      >
        <el-table-column type="selection" width="50" align="center" />
        <el-table-column type="index" label="序号" align="center" width="60" />
        <el-table-column prop="eventName" label="事件名称" align="center" />
        <el-table-column prop="pointName" label="气象监测点" align="center" />
        <el-table-column prop="temperature" label="温度(℃)" align="center" />
        <el-table-column prop="humidity" label="湿度(%)" align="center" />
        <el-table-column prop="windDirection" label="风向" align="center" />
        <el-table-column prop="windSpeed" label="风速(m/s)" align="center" />
        <el-table-column prop="pressure" label="气压(Pa)" align="center" />
        <el-table-column fixed="right" label="操作" align="center" width="180">
          <template slot-scope="scope">
            <el-button
              type="text"
              @click="handleDetail(scope.row)"
              style="color: #409eff"
              >详情</el-button
            >
            <el-button
              type="text"
              @click="handleEdit(scope.row)"
              style="color: #67c23a"
              >修改</el-button
            >
            <el-button
              type="text"
              @click="handleDel(scope.row)"
              style="color: #f56c6c"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryParams.pageNum"
        :page-sizes="[10, 20, 30, 50]"
        :page-size="queryParams.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="tableList.total"
        style="margin-top: 15px; text-align: right"
      />
    </el-card>

    <!-- 新增/修改弹框 -->
    <el-dialog
      :title="formTitle"
      :visible.sync="formDialogVisible"
      width="600px"
      append-to-body
      :close-on-click-modal="false"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="formRules"
        label-width="100px"
        class="form-container"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="*事件名称" prop="eventName">
              <el-select
                v-model="form.eventName"
                placeholder="请选择事件名称"
                style="width: 100%"
              >
                <el-option
                  label="2024年12月11日汤营超桥"
                  value="20241211tycq"
                ></el-option>
                <el-option
                  label="2024年12月15日河道治理"
                  value="20241215hdzl"
                ></el-option>
                <el-option
                  label="2024年12月20日环境监测"
                  value="20241220hjjc"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="*监测点名称" prop="pointName">
              <el-input
                v-model="form.pointName"
                placeholder="请输入气象监测点名称"
                maxlength="50"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="*温度" prop="temperature">
              <el-input-number
                v-model="form.temperature"
                :min="-40"
                :max="85"
                placeholder="请输入温度"
                step="0.1"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="*湿度" prop="humidity">
              <el-input-number
                v-model="form.humidity"
                :min="0"
                :max="100"
                placeholder="请输入湿度"
                step="0.1"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="*风向" prop="windDirection">
              <el-select
                v-model="form.windDirection"
                placeholder="请选择风向"
                style="width: 100%"
              >
                <el-option label="正北(N)" value="正北(N)"></el-option>
                <el-option label="东北(NE)" value="东北(NE)"></el-option>
                <el-option label="正东(E)" value="正东(E)"></el-option>
                <el-option label="东南(SE)" value="东南(SE)"></el-option>
                <el-option label="正南(S)" value="正南(S)"></el-option>
                <el-option label="西南(SW)" value="西南(SW)"></el-option>
                <el-option label="正西(W)" value="正西(W)"></el-option>
                <el-option label="西北(NW)" value="西北(NW)"></el-option>
                <el-option label="静风(C)" value="静风(C)"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="*风速" prop="windSpeed">
              <el-input-number
                v-model="form.windSpeed"
                :min="0"
                :max="100"
                placeholder="请输入风速"
                step="0.1"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="*气压" prop="pressure">
              <el-input-number
                v-model="form.pressure"
                :min="80000"
                :max="120000"
                placeholder="请输入气压"
                step="1"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="备注" prop="remark">
              <el-input
                v-model="form.remark"
                placeholder="请输入备注（可选）"
                maxlength="200"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="closeFormDialog">取消</el-button>
        <el-button type="primary" @click="submitForm">确定</el-button>
      </div>
    </el-dialog>

    <!-- 详情弹框 -->
    <el-dialog
      title="气象监测点详情"
      :visible.sync="detailDialogVisible"
      width="600px"
      append-to-body
      :close-on-click-modal="false"
    >
      <el-form :model="detailForm" label-width="100px" class="detail-form">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="事件名称">
              <el-input v-model="detailForm.eventName" readonly />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="监测点名称">
              <el-input v-model="detailForm.pointName" readonly />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="温度(℃)">
              <el-input v-model="detailForm.temperature" readonly />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="湿度(%)">
              <el-input v-model="detailForm.humidity" readonly />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="风向">
              <el-input v-model="detailForm.windDirection" readonly />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="风速(m/s)">
              <el-input v-model="detailForm.windSpeed" readonly />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="气压(Pa)">
              <el-input v-model="detailForm.pressure" readonly />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="备注">
              <el-input
                v-model="detailForm.remark"
                readonly
                :placeholder="detailForm.remark ? '' : '无'"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="detailDialogVisible = false">关闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: "WeatherMonitorManagement",
  dicts: ["sys_normal_disable"],
  components: {},
  data() {
    return {
      // 表格高度（自适应窗口）
      tableHeight: window.innerHeight - 400,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        eventName: "",
        pointName: "",
        minTemp: "",
        maxTemp: "",
      },
      // 表格数据
      tableList: {
        total: 0,
        rows: [],
      },
      tableData: [
        {
          id: 1,
          eventName: "2024年12月11日汤营超桥",
          pointName: "汤营超桥1#监测点",
          temperature: 18.5,
          humidity: 65.2,
          windDirection: "东北(NE)",
          windSpeed: 2.3,
          pressure: 101325,
          remark: "桥北侧监测点",
        },
        {
          id: 2,
          eventName: "2024年12月11日汤营超桥",
          pointName: "汤营超桥2#监测点",
          temperature: 19.2,
          humidity: 63.8,
          windDirection: "正东(E)",
          windSpeed: 1.8,
          pressure: 101280,
          remark: "桥南侧监测点",
        },
        {
          id: 3,
          eventName: "2024年12月15日河道治理",
          pointName: "河道上游监测点",
          temperature: 17.9,
          humidity: 70.5,
          windDirection: "西南(SW)",
          windSpeed: 3.1,
          pressure: 101450,
          remark: "河道治理上游500米",
        },
      ],
      // 选中的表格数据
      selectedRows: [],
      // 新增/修改弹框控制
      formDialogVisible: false,
      formTitle: "",
      form: {},
      // 表单校验规则
      formRules: {
        eventName: [
          { required: true, message: "请选择事件名称", trigger: "blur" },
        ],
        pointName: [
          { required: true, message: "请输入监测点名称", trigger: "blur" },
          {
            min: 2,
            max: 50,
            message: "监测点名称长度为2-50个字符",
            trigger: "blur",
          },
        ],
        temperature: [
          { required: true, message: "请输入温度", trigger: "blur" },
        ],
        humidity: [{ required: true, message: "请输入湿度", trigger: "blur" }],
        windDirection: [
          { required: true, message: "请选择风向", trigger: "blur" },
        ],
        windSpeed: [{ required: true, message: "请输入风速", trigger: "blur" }],
        pressure: [{ required: true, message: "请输入气压", trigger: "blur" }],
      },
      // 详情弹框控制
      detailDialogVisible: false,
      detailForm: {},
    };
  },
  mounted() {
    this.pageInit();
    // 监听窗口大小变化，调整表格高度
    window.addEventListener("resize", () => {
      this.tableHeight = window.innerHeight - 400;
    });
  },
  beforeDestroy() {
    window.removeEventListener("resize", () => {});
  },
  methods: {
    // 页面初始化
    pageInit() {
      this.getList();
    },

    // 获取表格数据（实际项目替换为接口请求）
    getList() {
      // 前端筛选演示（实际由后端实现）
      let filteredData = [...this.tableData];
      if (this.queryParams.eventName) {
        filteredData = filteredData.filter(
          (item) => item.eventName === this.queryParams.eventName
        );
      }
      if (this.queryParams.pointName) {
        filteredData = filteredData.filter((item) =>
          item.pointName.includes(this.queryParams.pointName)
        );
      }
      if (
        this.queryParams.minTemp !== "" &&
        this.queryParams.minTemp !== undefined
      ) {
        filteredData = filteredData.filter(
          (item) => item.temperature >= this.queryParams.minTemp
        );
      }
      if (
        this.queryParams.maxTemp !== "" &&
        this.queryParams.maxTemp !== undefined
      ) {
        filteredData = filteredData.filter(
          (item) => item.temperature <= this.queryParams.maxTemp
        );
      }

      // 分页处理（实际由后端实现）
      this.tableList.total = filteredData.length;
      const startIndex =
        (this.queryParams.pageNum - 1) * this.queryParams.pageSize;
      const endIndex = startIndex + this.queryParams.pageSize;
      this.tableList.rows = filteredData.slice(startIndex, endIndex);
    },

    // 表格选中事件
    handleSelectionChange(selection) {
      this.selectedRows = selection;
    },

    // 搜索查询
    handleSearch() {
      this.queryParams.pageNum = 1;
      this.getList();
    },

    // 重置查询条件
    handleReset() {
      this.queryParams = {
        pageNum: 1,
        pageSize: 10,
        eventName: "",
        pointName: "",
        minTemp: "",
        maxTemp: "",
      };
      this.getList();
    },

    // 分页大小改变
    handleSizeChange(val) {
      this.queryParams.pageSize = val;
      this.getList();
    },

    // 当前页改变
    handleCurrentChange(val) {
      this.queryParams.pageNum = val;
      this.getList();
    },

    // 新增按钮操作
    handleAdd() {
      this.resetForm();
      this.formDialogVisible = true;
      this.formTitle = "新增气象监测点";
    },

    // 批量修改按钮操作
    handleBatchUpdate() {
      if (this.selectedRows.length === 0) {
        this.$message.warning("请选择一条数据进行修改");
        return;
      }
      if (this.selectedRows.length > 1) {
        this.$message.warning("只能选择一条数据进行修改");
        return;
      }
      this.resetForm();
      this.form = { ...this.selectedRows[0] };
      this.formDialogVisible = true;
      this.formTitle = "修改气象监测点";
    },

    // 批量删除按钮操作
    handleBatchDelete() {
      if (this.selectedRows.length === 0) {
        this.$message.warning("请选择需要删除的数据");
        return;
      }
      this.$confirm(
        `确定要删除选中的 ${this.selectedRows.length} 条数据吗？`,
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(() => {
          // 实际项目替换为删除接口
          const ids = this.selectedRows.map((item) => item.id);
          this.tableData = this.tableData.filter(
            (item) => !ids.includes(item.id)
          );
          this.getList();
          this.selectedRows = [];
          this.$message.success("删除成功");
        })
        .catch(() => {
          this.$message.info("已取消删除");
        });
    },

    // 查看详情
    handleDetail(row) {
      this.detailForm = { ...row };
      this.detailDialogVisible = true;
    },

    // 单行修改
    handleEdit(row) {
      this.resetForm();
      this.form = { ...row };
      this.formDialogVisible = true;
      this.formTitle = "修改气象监测点";
    },

    // 单行删除
    handleDel(row) {
      this.$confirm(`确定要删除「${row.pointName}」吗？`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          // 实际项目替换为删除接口
          this.tableData = this.tableData.filter((item) => item.id !== row.id);
          this.getList();
          this.$message.success("删除成功");
        })
        .catch(() => {
          this.$message.info("已取消删除");
        });
    },

    // 导出数据
    handleExport() {
      this.$message.info("导出功能执行中...");
      // 实际项目替换为导出接口
    },

    // 重置表单
    resetForm() {
      this.form = {
        id: "",
        eventName: "",
        pointName: "",
        temperature: "",
        humidity: "",
        windDirection: "",
        windSpeed: "",
        pressure: "",
        remark: "",
      };
      if (this.$refs.formRef) {
        this.$refs.formRef.resetFields();
      }
    },

    // 关闭新增/修改弹框
    closeFormDialog() {
      this.formDialogVisible = false;
      this.resetForm();
    },

    // 提交表单（新增/修改）
    submitForm() {
      this.$refs.formRef.validate((valid) => {
        if (valid) {
          // 校验监测点名称唯一性（新增时）
          if (!this.form.id) {
            const isDuplicate = this.tableData.some(
              (item) =>
                item.pointName === this.form.pointName &&
                item.eventName === this.form.eventName
            );
            if (isDuplicate) {
              this.$message.error("该事件下已存在同名监测点");
              return;
            }
          }

          if (this.form.id) {
            // 修改逻辑
            const index = this.tableData.findIndex(
              (item) => item.id === this.form.id
            );
            if (index > -1) {
              this.tableData.splice(index, 1, { ...this.form });
            }
            this.$message.success("修改成功");
          } else {
            // 新增逻辑（模拟生成id）
            this.form.id = new Date().getTime();
            this.tableData.unshift({ ...this.form });
            this.$message.success("新增成功");
          }
          this.formDialogVisible = false;
          this.getList();
          this.resetForm();
        }
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.weather-monitor-container {
  padding: 15px;
  background-color: #f9f9f9;
  min-height: calc(100vh - 20px);

  // 搜索卡片样式
  .search-card {
    margin-bottom: 15px;
    box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);

    .search-bar {
      display: flex;
      align-items: center;
      padding: 10px 0;

      .search-module-label {
        font-size: 16px;
        font-weight: 600;
        color: #333;
        margin-right: 20px;
      }

      .search-form {
        flex: 1;

        .el-form-item {
          margin-right: 15px;
          margin-bottom: 0;
        }

        .el-form-item__label {
          color: #666;
          font-weight: 500;
        }
      }
    }
  }

  // 表格卡片样式
  .table-card {
    box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);

    .operate-bar {
      margin-bottom: 12px;
      padding-left: 5px;

      .el-button {
        margin-right: 10px;
      }
    }

    .el-table {
      border-radius: 4px;
      overflow: hidden;

      .el-table__row {
        &:hover {
          background-color: #fafafa;
        }
      }

      .el-table-column {
        .cell {
          white-space: nowrap;
        }
      }
    }
  }

  // 表单弹框样式
  .form-container {
    .el-form-item {
      margin-bottom: 18px;
    }

    .el-form-item__label {
      color: #333;
      font-weight: 500;
      &::before {
        content: "*";
        color: #f56c6c;
        margin-right: 4px;
      }
      // 非必填项移除*
      &.el-form-item__label--no-asterisk::before {
        content: "";
        margin-right: 0;
      }
    }

    .el-input-number {
      width: 100%;
    }
  }

  // 详情弹框样式
  .detail-form {
    .el-form-item {
      margin-bottom: 18px;
    }

    .el-form-item__label {
      color: #333;
      font-weight: 500;
    }

    .el-input[readonly] {
      background-color: #f9f9f9;
      color: #666;
      cursor: not-allowed;
    }
  }

  // 弹框底部样式
  .dialog-footer {
    text-align: right;
    margin-top: 10px;
  }

  // 响应式调整
  @media (max-width: 1200px) {
    .search-bar {
      flex-direction: column;
      align-items: flex-start !important;

      .search-module-label {
        margin-bottom: 10px;
      }

      .search-form .el-form-item {
        margin-bottom: 10px;
      }
    }
  }

  @media (max-width: 992px) {
    .tableHeight {
      height: auto !important;
    }

    // 弹框表单自适应单列
    .form-container .el-row,
    .detail-form .el-row {
      flex-direction: column;
    }

    .form-container .el-col,
    .detail-form .el-col {
      width: 100% !important;
      margin-bottom: 8px;
    }
  }
}
</style>
